package com.itboye.jinpuyiyuan.utils.download_pdf;

import android.app.DownloadManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v4.content.FileProvider;
import android.util.Log;
import android.webkit.MimeTypeMap;


import java.io.File;

/**
 * Created by ss159 on 2017/5/15.
 */

public class DownloadService extends Service {
    DownloadManager downloadManager;
    long  mTaskId=0;
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {

        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        //将下载请求加入下载队列
        downloadManager = (DownloadManager) getApplicationContext().getSystemService(Context.DOWNLOAD_SERVICE);

    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        String action=intent.getAction();
        if(null!=action&&action.equals("download_pdf")){
            String url=  intent.getStringExtra("url");
            Log.d("======serve",url);
            String fileName="";
            if(url!=null&&url.contains("/")){
             int  index=   url.lastIndexOf("/");
                fileName=url.substring(index,url.length());
//                if(!fileName.equals("")){
               //     String 	downloadPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath() + File.separator + fileName;
                  ;
                    downloadFile(intent.getStringExtra("url"),fileName);
//                }else {
//                    this.stopService(new Intent(this, DownloadService.class));
//                }

            }else {
                this.stopService(new Intent(this, DownloadService.class));
            }


        }


        return super.onStartCommand(intent, flags, startId);
    }
    private void downloadFile(String versionUrl, String versionName) {            //创建下载任务
        MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
        String mimeString = mimeTypeMap.getMimeTypeFromExtension(MimeTypeMap.getFileExtensionFromUrl(versionUrl));

        String downloadPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath() + File.separator + versionName;
        File  file= new File(downloadPath);
                if(file!=null){
                    openFile(downloadPath,mimeString);
                    this.stopService(new Intent(this, DownloadService.class));
                    return;
                }
        DownloadManager.Request request = new DownloadManager.Request(Uri.parse(versionUrl));
        request.setAllowedOverRoaming(false);
        //漫游网络是否可以下载

        //设置文件类型，可以在下载结束后自动打开该文件

        request.setMimeType(mimeString);
        //在通知栏中显示，默认就是显示的
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE);
        request.setVisibleInDownloadsUi(true);
        //sdcard的目录下的download文件夹，必须设置
            request.setDestinationInExternalPublicDir("/download/", versionName);
        //request.setDestinationInExternalFilesDir(),也可以自己制定下载路径

        if(downloadManager!=null){
            //加入下载队列后会给该任务返回一个long型的id，
            //通过该id可以取消任务，重启任务等等，看上面源码中框起来的方法
            mTaskId = downloadManager.enqueue(request);
        }



    }

    /**
     * 打开文件
     * @param file
     */
    private void openFile(String file, String type){

//        Intent intent = new Intent();
//        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//        //设置intent的Action属性
//        intent.setAction(Intent.ACTION_VIEW);
        //获取文件file的MIME类型
        //		String type = getMIMEType(file);
        //设置intent的data和Type属性。
//        intent.setDataAndType(Uri.fromFile(file), type);
        Intent pdf = new Intent("pdf");
        pdf.putExtra("file",file);
        sendBroadcast(pdf);

//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
//            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
//            Uri contentUri = FileProvider.getUriForFile(getApplicationContext(), "jinpuyiyuan.fileprovider.FileProvider",new File(file));
//            intent.setDataAndType(contentUri, type);
//        } else {
//            intent.setDataAndType(Uri.fromFile(new File(file)), type);
//            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//        }
//        //跳转
//        getApplicationContext().startActivity(intent); //这里最好try一下，有可能会报错。 //比如说你的MIME类型是打开邮箱，但是你手机里面没装邮箱客户端，就会报错。
//        try {
//
//        }catch (Exception e){
//            Toast.makeText(getApplicationContext(),e.getMessage(),Toast.LENGTH_SHORT).show();
//        }


    }
}
